﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Etapa1.SofRender.Sample
{
    public class SimpleLightingShader : SEffect,PixelShader,VertexShader
    {
        public SimpleLightingShader()
        {
            this.GeometricShader = null;
            this.PixelShader = this;
            this.VertexShader = this;
        }

        public Matrix matWorldViewProj;
        public Matrix matWorld;
        public Vector4 vLightDirection;
        public Vector4 EyePos;

        #region VertexShader Members

        VertexType VertexShader.VertexShader(VertexType vertice)
        {                    
            Vector4 normal = vertice[Slots.NORMAL0];
            normal = Vector4.Transform(normal, matWorld);            

            Vector4 posWorld = Vector4.Transform(vertice[Slots.POSITION0], matWorld);            

            VertexType Out = new VertexType();
            Out[Slots.TEXTCOORD0] = EyePos - posWorld;
            Out[Slots.POSITION0] = Vector4.Transform(vertice[Slots.POSITION0], matWorldViewProj);         
            Out[Slots.NORMAL0] = normal;
            return Out; 
        }

        #endregion

        #region PixelShader Members

        Microsoft.Xna.Framework.Graphics.Color PixelShader.PixelShader(VertexType vo)
        {            
            Vector3 ld = ShaderOp.Normalize(ShaderOp.toVector3(vLightDirection));            
            Vector3 vd = ShaderOp.Normalize(ShaderOp.toVector3(vo[Slots.TEXTCOORD0]));      
            Vector3 normal = ShaderOp.Normalize(ShaderOp.toVector3(vo[Slots.NORMAL0]));

            float Diff = ShaderOp.saturate(ShaderOp.dot(normal, ld)); 
            Vector3 Reflect = ShaderOp.Normalize( (2 * Diff * normal) - ld);  
            
            float Specular = ShaderOp.pow(ShaderOp.saturate(ShaderOp.dot(Reflect, vd)), 50) * 0.6f; 

            float Ai = 1f;
            Vector3 Ac = new Vector3(0.075f, 0.075f, 0.2f);
            float Di = 1f;
            Vector3 Dc = new Vector3(0.5f, 0.5f, 0.5f);            
            
            return new Color(Ai * Ac + Di * Dc * Diff + Color.White.ToVector3() * Specular); 
            
        }

        #endregion
    }
}
